package xzy.com.controller;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.BufferedInputStream;
import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;

import xzy.com.entity.domain.Article;
import xzy.com.entity.domain.Datum;
import xzy.com.entity.domain.Menu;
import xzy.com.entity.vo.ResponseBean;
import xzy.com.exception.CustomUnauthorizedException;
import xzy.com.service.DatumService;
/**
 * 
* @Title: DatumController
* @Description: 资料管理控制层
* @author: liyang
* @date 2020年12月6日 下午4:50:47
 */
@RestController
@RequestMapping("/datum")
public class DatumController {
	@Autowired
	private DatumService datumService;
	
	
	//文件上传
	@PostMapping("/fileUpload")
	public ResponseBean add(@RequestParam("file") MultipartFile file) throws FileNotFoundException{
		// 判断文件是否为空，空则返回失败页面
		if (file.isEmpty()) {
			throw new CustomUnauthorizedException("文件为空！");
		}
		//文件路径
		//String path = "E:/WorkSpace/eclipse/git/xld-web-back/xld-web-back/xld-website/xld-website-backManager/src/main/resources/file/";
		String path1 = ResourceUtils.getURL("classpath:").getPath();
		String path2 = path1.substring(1,path1.indexOf("target"));
		String path3 = path2+"src/main/resources/file/";
		
		// 获取源文件名
		String orginName = file.getOriginalFilename();
		
		Datum datum = new Datum();
		datum.setFilename(orginName);
		datum.setTitle(orginName.substring(0,orginName.indexOf(".")));
		datum.setUrl(path3+orginName);
		// 创建文件实例
		File filePath = new File(path3+orginName);
		// 如果文件目录不存在，创建目录
		if (!filePath.getParentFile().exists()) {
			filePath.getParentFile().mkdirs();
		}
		
		try {
            file.transferTo(filePath); //保存文件
			datumService.save(datum);
			return new ResponseBean(HttpStatus.OK.value(), "文件成功!", null);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
		return null;
		
	}
	
	//文件下载
	@GetMapping("/fileDownload")
	public void fileDownload(@RequestParam("id") Long id,HttpServletResponse response) throws UnsupportedEncodingException {
		
		if(null==id) {
			throw new CustomUnauthorizedException("id不能为空！");
		}
		Datum datum = datumService.getById(id);
		if(null==datum) {
			throw new CustomUnauthorizedException("文件不存在");
		}
		
        File file = new File(datum.getUrl());
        if(file.exists()){
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(datum.getFilename(),"utf8"));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try(
            	FileInputStream fis= new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            datum.setNumber(datum.getNumber()+1);
            datumService.updateById(datum);
        }
	}

	// 分页处理
	@GetMapping("/page")
	public ResponseBean listPages(@RequestParam("pages") Integer pages, @RequestParam("size") Integer size) {
		Page<Datum> page = new Page<>(pages, size);
		QueryWrapper<Datum> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByAsc("id");
		datumService.page(page, queryWrapper);
		Page<Datum> pages1 = datumService.page(page, queryWrapper);
		
		Map<String,Object> map = new HashMap<>();
		map.put("list", pages1.getRecords());
		map.put("recordTotal", pages1.getTotal());
		map.put("pageTotal", pages1.getPages());
		return new ResponseBean(HttpStatus.OK.value(), "分页请求成功", map);
	}

	// 搜索查询分页处理
	
	@GetMapping("/search")
	public ResponseBean  searchListPages(@RequestParam("title") String title,@RequestParam("pages") Integer pages, @RequestParam("size") Integer size) {
		Page<Datum> page = new Page<>(pages, size);
		QueryWrapper<Datum> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByAsc("id");
		if(null!=title) {
			queryWrapper.like("title", title);
		}
		Page<Datum> pages1 = datumService.page(page, queryWrapper);
        //IPage<Menu> menuPage = menuService.findParentMenu(pages1, queryWrapper);
		//查询父级菜单
				
		Map<String,Object> map = new HashMap<>();
		map.put("list", pages1.getRecords());
		map.put("recordTotal", pages1.getTotal());
		map.put("pageTotal", pages1.getPages());
		return new ResponseBean(HttpStatus.OK.value(), "分页请求成功", map);
	}
	
	// 根据类别查询资料
			@GetMapping("/findByType")
			public ResponseBean findByType(@RequestParam("pages") Integer pages, @RequestParam("size") Integer size,@RequestParam(value="id",required = false) Long id) {
				Page<Datum> page = new Page<>(pages, size);
				QueryWrapper<Datum> queryWrapper = new QueryWrapper<>();
				Datum datum= null;
				if(null!=id) {
					queryWrapper.eq("menu_id", id);
				}
				queryWrapper.orderByDesc("create_time");
				Page<Datum> datumPage = datumService.page(page, queryWrapper);
				Map<String, Object> map = new HashMap<>();
				map.put("list", datumPage.getRecords());
				map.put("recordTotal", datumPage.getTotal());
				map.put("pageTotal", datumPage.getPages());
				System.out.println("分页资料测试："+datumPage.getRecords());
				return new ResponseBean(HttpStatus.OK.value(), "分页请求成功", map);
			}

		// 根据id查询资料
		@GetMapping("/findById")
		public ResponseBean findById(@RequestParam("id") Long id) {
			if (null != id) {
				Datum datum = datumService.getById(id);
				
				if (datum != null) {
					return new ResponseBean(HttpStatus.OK.value(), "查询成功!", datum);
				} else {
					return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "查询失败", null);
				}
			}
			return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "id不能为空", null);
		}
}
